<?php

/**
 * Class Service_Api_Payment_Icbc
 * @brief 支付接口-工商银行
 */
class Service_Api_Payment_Icbc extends Contract_Api_Payment
{
    use Trait_Api_Common;
    use Trait_Api_Payment;
    /**
     * 获取支付数据
     * @param $params
     * @return array
     * @throws Exception
     */
    function get_pay_data($params): array
    {
        // 验证订单状态
        $order_sn = $params['ordersn'];
        // 验证订单
        $checkOrder = Model_Api_V2_Payment::ordersn_checked($order_sn);

        if ( ! $checkOrder['status']) {
            throw new Exception($checkOrder['msg']);
        }
        $orderInfo = Model_Member_Order::order_info($order_sn);

        //"0元"订单,免费产品
        if ($orderInfo['pay_price'] == 0) {
            $zero_res = $this->zero_pay($order_sn);
            if ($zero_res['status']) {
                $orderInfo['sign'] = $zero_res['data']['sign'];
                return array(
                    'is_pay' => 1,
                    'info' => $orderInfo,
                    'pay_method' => [],
                    'additional' => [],
                    'btn_title' => '查看订单'
                );
            } else {
                throw new Exception($zero_res['msg']);
            }
        }

        if ($orderInfo && $orderInfo['status'] == 1 && $orderInfo['memberid'] == $params['mid']) {
            // 获取会员的微信小程序参数配置
            $member_third = DB::select()->from("member_third")->where("mid", "=",
                $params['mid'])->and_where("come_from", "=", "weixin")->execute()->current();

            if ($member_third && $member_third['wx_mini_openid']) {
                //小程序端支付
                $pay_type = Model_Icbcpay::PAY_TYPE_MINIPROGRAM;
                $pay = new Model_Icbcpay();
                $pay_order_params = $pay->generate_order_params($order_sn,$pay_type);
                //同步跳转地址,必传参数，实际不起作用
                $pay_order_params['jumpUrl'] = Common::get_main_host();
                $arr = Service_Pay_Center::create_pay_order($pay_order_params);
                $arr = json_decode($arr,true);
                if($arr['status']){
                    $payInfo = json_decode($arr['data']['payInfo'],true);
                    $unifiedOrderResult = [
                        'paySign' => $payInfo['paySign'],
                        'package' => $payInfo['package'],
                        'timeStamp' => (string)$payInfo['timeStamp'],
                        'nonce_str' => $payInfo['nonceStr'],
                        'is_pay' => 0,
                    ];
                }
                return $unifiedOrderResult;
            } else {
                throw new Exception('会员信息有误');
            }
        } else {
            throw new Exception("订单信息有误");
        }
    }
}